import urllib2

script = urllib2.urlopen("https://creator-dev.googlecode.com/svn/trunk/scripts/is_pt_in_poly.py")
exec(script.read())
script.close()

script = urllib2.urlopen("https://creator-dev.googlecode.com/svn/trunk/scripts/bounding_box_tree.py")
exec(script.read())
script.close()

def compute_height_above_ground_in_poly(poly, pt):
	height = None
	if is_pt_in_poly_2d(pt, poly):
		vertex = mgGetChild(poly)
		ok, x, y, z = mgGetVtxCoord(vertex)
		if not ok:
			return height
		pt1 = mgMakeCoord3d(x, y, z)
		vertex = mgGetNext(vertex)
		ok, x, y, z = mgGetVtxCoord(vertex)
		if not ok:
			return height
		pt2 = mgMakeCoord3d(x, y, z)
		vertex = mgGetNext(vertex)
		ok, x, y, z = mgGetVtxCoord(vertex)
		if not ok:
			return height
		pt3 = mgMakeCoord3d(x, y, z)
		vec1 = mgCoord3dSubtract(pt2, pt1)
		vec2 = mgCoord3dSubtract(pt3, pt1)
		normal = mgCoord3dCross(vec1, vec2)
		if not normal.z == 0.0:
			height = ((x - pt.x) * normal.x + (y - pt.y) * normal.y) / normal.z + z
	return height


def compute_height_above_ground(box_tree, pt):
	def ignore_func(box, pt):
		return not (box.min.x <= pt.x and box.max.x >= pt.x and box.min.y <= pt.y and box.max.y >= pt.y)

	height_list = []
	box_tree.ignore_func = ignore_func
	box_tree.ignore_func_arg = pt
	for box in box_tree:
		poly = box_tree.get_poly(box)
		if poly:
			height = compute_height_above_ground_in_poly(poly, pt)
			if height:
				height_list.append(height)
	return height_list